﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Web;
using System.Web.Services;
using Remoter;

/// <summary>
/// Summary description for LampRemoterService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class LampRemoterService : System.Web.Services.WebService {

    private SerialPort serialPort = new SerialPort();
    Remoter.Remoter remoter;

    public LampRemoterService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
        OpenPort();
        remoter = new Remoter.Remoter();
        remoter.setCommand(0, new NoCommand(), new NoCommand());
        remoter.setCommand(1, new Slot1OnCommand(this.serialPort), new Slot1OffCommand(this.serialPort));
        remoter.setCommand(2, new Slot2OnCommand(this.serialPort), new Slot2OffCommand(this.serialPort));
        remoter.setCommand(3, new Slot3OnCommand(this.serialPort), new Slot3OffCommand(this.serialPort));

        //OpenPort();
    }

    [WebMethod]
    public string OpenPort()
    {
        bool error = false;

        // If the port is open, close it.
        if (serialPort.IsOpen)
        {
            serialPort.Close();
            return "Closed";
        }
        else
        {
            // Set the port's settings
            serialPort.BaudRate = 9600;
            serialPort.DataBits = 8;
            serialPort.StopBits = StopBits.One;
            serialPort.Parity = Parity.None;
            serialPort.PortName = "COM3";

            try
            {
                // Open the port
                serialPort.Open();
            }
            catch (UnauthorizedAccessException) { error = true; }
            catch (IOException) { error = true; }
            catch (ArgumentException) { error = true; }

            if (error)
                return "Could not open the COM port.  Most likely it is already in use, has been removed, or is unavailable.";
            else
                return "OK!";

        }
    }

    [WebMethod]
    public string TurnOn(int slot) 
    {
        if(!this.serialPort.IsOpen) this.serialPort.Open();
        string result = this.remoter.TurnOn(slot);
        this.serialPort.Close();
        return result;
    }

    [WebMethod]
    public string TurnOff(int slot)
    {
        if (!this.serialPort.IsOpen) this.serialPort.Open();
        string result = this.remoter.TurnOff(slot);
        this.serialPort.Close();
        return result;
    }
}
